#include "ClientThread.h"

ClientThread::ClientThread(qintptr _id, QObject *parent) : QThread(parent)
{
    socketId = _id;
    quit = false;
}

void ClientThread::run()
{
	// ClientThread must create a new clientHandle and connect it to readyRead and disconnected.
	// This means that ClientThread is alerted when a new message is received.
    client = new ClientHandle(socketId);
    connect(client, SIGNAL(readyRead()), this, SLOT(readyRead()), Qt::DirectConnection);
    connect(client, SIGNAL(disconnected()), this, SLOT(disconnected()), Qt::DirectConnection);

    while (!quit)
    {
		// Write messages to the network when it's ready
        client->waitForReadyRead(1);
        for (int i = msgToWrite.size() - 1; i >= 0; i--)
        {
            client->write(msgToWrite.at(i));
            msgToWrite.removeAt(i);
        }
    }
}

void ClientThread::readyRead()
{
	// Read the data from the socket into a byte array and emit the received message
    QByteArray buffer;
    while (client->bytesAvailable())
    {
        buffer.append(client->readAll());
    }

    emit receivedMessage(buffer);
}

void ClientThread::disconnected()
{
    emit clientClosed(socketId);
    client->deleteLater();
    quit = true;
}

void ClientThread::sendMessage(const QByteArray &msg)
{
	// The delay stops messages from joining on the network since the TCP buffer isn't emptied.
	// Sometimes two messages will be appended in the buffer. This causes parsing problems on the
	// client side, msleep fixes this problem.
    QThread::msleep(100);
    msgToWrite.prepend(msg);
}

bool ClientThread::writeJSON(QJsonObject json)
{
	// Write the JSON object to the client socket
    QJsonDocument doc(json);
    QString req = QString::fromUtf8(doc.toJson());
    client->write(req.toLatin1());
    return true;
}
